from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import GridSearchCV


def knn_iris_gscv():
    '''
    KNN算法对鸢尾花分类
    :return:
    '''
    iris=load_iris()
    x_train,x_test,y_train,y_test=train_test_split(iris.data,iris.target,test_size=0.2,random_state=22)
    transfer=StandardScaler()
    x_train=transfer.fit_transform(x_train)
    x_test = transfer.transform(x_test)
    estimator=KNeighborsClassifier(n_neighbors=3)

    #网格搜索与交叉验证
    estimator=GridSearchCV(estimator=estimator,
                 param_grid={'n_neighbors':[1,3,5,7,9,11]},cv=10)
    estimator.fit(x_train,y_train)

    y_predict=estimator.predict(x_test)
    print(y_test==y_predict)
    score=estimator.score(x_test,y_test)
    print(score)

    print(estimator.best_params_)
    print(estimator.best_score_)
    print(estimator.best_estimator_)
    print(estimator.cv_results_)


knn_iris_gscv()